package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.os.Bundle
import android.view.View
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityAnnouncementDetailBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat


/**
 * @Author      : hxw
 * @Date        : 2024/11/28 9:12
 * @Describe    : 规程详情
 */
class ActivityAnnouncementDetail : BaseActivity<OrgDetailViewModel, ActivityAnnouncementDetailBinding>() {

    private var pdfUrl = ""

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "规程详情"

        requestPermission()

        mDatabind.swipeRefreshLayout.init {
            onRefresh()
        }
    }

    private fun requestPermission() {
        XXPermissions.with(this)
            /** 适配分区存储应该这样写 */
            .permission(Permission.READ_MEDIA_AUDIO)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .interceptor(PermissionInterceptor())
            .request(OnPermissionCallback { _, allGranted ->
                if (!allGranted) {
                    RxToast.showToast(getString(R.string.permission_acquisition_failure))
                    dismissLoading()
                    return@OnPermissionCallback
                }
                onRefresh()
            })
    }

    private fun onRefresh() {
        val id = intent.getStringExtra("id").toString()
        showLoading(getString(R.string.loading))
        mViewModel.getAnnouncementDetail(id)
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取规程详情  */
        mViewModel.announcementDetailResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            pdfUrl = it.regimentoUrl
            if (pdfUrl.endsWith(".pdf") || pdfUrl.endsWith(".PDF")) {
                mDatabind.llWebView.isGone = false
                mDatabind.ivAnnouncement.isGone = true
                initWebView()
            } else {
                mDatabind.llWebView.isVisible = true
                mDatabind.ivAnnouncement.isVisible = false
                ImageLoaderManager.loadImage(this, pdfUrl, mDatabind.ivAnnouncement)
            }
        }
    }

    private fun initWebView() {
        val webSettings = mDatabind.webView.settings
        webSettings.userAgentString += "Android-Pigeon"
        webSettings.javaScriptEnabled = true//允许使用js
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.loadWithOverviewMode = false//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式
        webSettings.allowUniversalAccessFromFileURLs = true //设置可以访问URL
        mDatabind.webView.webChromeClient = webChromeClient
        mDatabind.webView.loadUrl("file:///android_asset/index.html?$pdfUrl")
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            mDatabind.progressBar.visibility = View.VISIBLE
            mDatabind.progressBar.progress = newProgress
            if (newProgress == 100) {
                mDatabind.progressBar.visibility = View.GONE
            }
        }
    }

    override fun onDestroy() {
        mDatabind.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        mDatabind.webView.clearHistory()
        mDatabind.webView.destroy()
        super.onDestroy()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.ivAnnouncement) {
            when (it) {
                mDatabind.ivAnnouncement -> {}//showBigImage()
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    private fun showBigImage() {
        if (pdfUrl.isNotEmpty() && pdfUrl.endsWith(".png") || pdfUrl.endsWith(".jpg") || pdfUrl.endsWith(".jpeg")) {
            openBigImage(mDatabind.ivAnnouncement, pdfUrl)
        }
    }
}